package com.jwd.avmanager.entity;

import com.jwd.avmanager.util.ByteUtil;

/**
 * 发送消息封装类
 */
public class MsgPacket {
    public static final int HEADER_LENGTH = 12;
    private short cmdType;//2个字节，命令的ID
    private short serialNo;//2个字节，命令的附加码
    private int cmdLength;//4个字节，命令长度，长度包括协议头和协议体数据
    private int devIdx = -1;//4个字节，设备的索引，由平台的分配，分配配时是（-1）
    private byte[] bytes = null;//整体的协议数据
    private byte[] body = null;//除去头部的数据包

    public MsgPacket(short cmdType, short serialNo, int cmdLength, int devIdx) {
        this.cmdType = cmdType;
        this.serialNo = serialNo;
        this.cmdLength = cmdLength;
        this.devIdx = devIdx;
        bytes = new byte[cmdLength];

        //将所有的非byte类型转为byte数组
        byte[] cmdTypeBytes = ByteUtil.shortToBytes(cmdType);
        byte[] serialBytes = ByteUtil.shortToBytes(serialNo);
        byte[] cmdLenBytes = ByteUtil.intToBytes(cmdLength);
        byte[] devIdxBytes = ByteUtil.intToBytes(devIdx);
        //先将头部指令拷贝到协议数组
        System.arraycopy(cmdTypeBytes, 0, bytes, 0, cmdTypeBytes.length);//0-2
        System.arraycopy(serialBytes, 0, bytes, cmdTypeBytes.length, serialBytes.length);//2-4
        System.arraycopy(cmdLenBytes, 0, bytes, cmdTypeBytes.length + serialBytes.length, cmdLenBytes.length);//4-8
        System.arraycopy(devIdxBytes, 0, bytes, cmdTypeBytes.length + serialBytes.length + cmdLenBytes.length, devIdxBytes.length);//8-12
    }

    public short getCmdType() {
        return cmdType;
    }

    public void setCmdType(short cmdType) {
        this.cmdType = cmdType;
    }

    public short getSerialNo() {
        return serialNo;
    }

    public void setSerialNo(short serialNo) {
        this.serialNo = serialNo;
    }

    public int getCmdLength() {
        return cmdLength;
    }

    public void setCmdLength(int cmdLength) {
        this.cmdLength = cmdLength;
    }

    public int getDevIdx() {
        return devIdx;
    }

    public void setDevIdx(int devIdx) {
        this.devIdx = devIdx;
    }

    public byte[] getBytes() {
        return bytes;
    }

    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }

    public byte[] getBody() {
        return body;
    }

    public void setBody(byte[] body) {
        this.body = body;
    }

    public void putBody(byte[] body) {
        this.body = body;
        if (bytes != null) {
            System.arraycopy(body, 0, bytes, HEADER_LENGTH, body.length);
        }
    }
}
